package main

import (
	"fmt"
	"os"
	"sync"

	"webpagedown3/internal/downloader"

	"github.com/spf13/cobra"
)

func main() {
	var (
		concurrency int
		maxDepth    int
		outputDir   string
		maxRetries  int
		urls        []string
		resources   bool
	)

	rootCmd := &cobra.Command{
		Use:   "downloader",
		Short: "A concurrent website downloader",
		PreRun: func(cmd *cobra.Command, args []string) {
			if len(urls) == 0 {
				fmt.Println("请提供至少一个URL")
				os.Exit(1)
			}
		},
		Run: func(cmd *cobra.Command, args []string) {
			config := downloader.NewConfig(concurrency, maxDepth, outputDir, maxRetries, urls, resources)
			err := downloader.Download(config, &sync.Map{})
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		},
	}

	rootCmd.Flags().IntVarP(&concurrency, "concurrency", "c", 5, "并发下载数")
	rootCmd.Flags().IntVarP(&maxDepth, "depth", "d", 1, "递归下载深度")
	rootCmd.Flags().StringVarP(&outputDir, "output", "o", "downloads", "输出目录")
	rootCmd.Flags().IntVarP(&maxRetries, "retries", "r", 3, "下载失败重试次数")
	rootCmd.Flags().StringSliceVarP(&urls, "urls", "u", []string{}, "要下载的URL列表")
	rootCmd.Flags().BoolVarP(&resources, "resources", "s", true, "是否下载资源文件(图片、CSS、JS等)")

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
